<template>
  <div class="btnUpload">
    <el-upload class="upload"
              :action="uploadApi"
              :accept="fileType"
              :show-file-list="showFiles"
              :file-list="fileLists"
              :on-remove="fileRemove"
              :drag="drag" :list-type="listType"
              :before-upload="beforeUpload"
              :on-success="uploadSuccess"
              :headers="headers" :limit="limit"
              :data="sendData"
              v-if="btnDisplay && !disabled">
      <el-button type="primary" v-if="btnDisplay && !drag" class="btns"><i class="el-icon-upload2" style="font-size: 12px;"></i>上传</el-button>
      <!-- <auth-button v-if="btnDisplay && !drag" :size="btnSize" class="iconCircle" :icon="'iconfont iconshangchuan'" :title="'上传'" :menuCode="menuCode" :perms="perms"></auth-button> -->
      <i class="el-icon-upload" v-if="drag"></i>
      <div v-if="drag" class="el-upload__text">将文件拖到此处，或<em>{{$t('common.batchUpload')}}</em></div>
      <img class="fileImg" :authSrc="imageUrl" v-if="showFile"/>
    </el-upload>
    <img class="fileImg" :authSrc="imageUrl" alt="" v-if="showFile && !disabled"/>
  </div>
</template>

<script>
  import AuthButton from '@/components/auth/authButton'
  import { getHeaders } from '@/utils/devUtils'
  import { getToken } from '@/utils/auth'
  export default {
    components: {AuthButton},
    props: {
      value: {
        type: [String, Array],
        default: ''
      },
      // 所属菜单Code-->全局唯一
      menuCode: {
        type: String,
        default: null
      },
      // 按钮权限标识，外部使用者传入
      perms: {
        type: String,
        default: null
      },
      // 文件ID
      fileID: {
        type: [String, Number],
        default: function () {
          return null
        }
      },
      // 是否显示上传文件
      showFiles: {
        type: Boolean,
        default: true
      },
      // 文件名
      fileName: {
        type: String,
        default: function () {
          return null
        }
      },
      // 所属类型CODE
      belongCode: {
        type: String,
        // required: true,
        default: function () {
          return 'GYS'
        }
      },
      // 是否拖拽
      drag: {
        type: Boolean,
        default: function () {
          return false
        }
      },
      // 所属业务ID
      belongID: {
        type: String,
        // required: true,
        default: function () {
          return null
        }
      },
      // 限制文件类型
      fileType: {
        type: String,
        default: function () {
          return null
        }
      },
      // 限制文件大小(M)
      fileSize: {
        type: Number,
        default: function () {
          return 50
        }
      },
      // 文件管理服务上传地址
      uploadApi: {
        type: String,
        // required: true,
        default: function () {
          return '/restapi/file/fastdfs/upload/file'
        }
      },
      showImageApi: {
        type: String,
        default: function () {
          return '/restapi/file/fastdfs/download/imageById?id='
        }
      },
      // 行数据
      rowData: {
        type: Object,
        default: function () {
          return null
        }
      },
      // 行号
      rowIndex: {
        type: Number,
        default: function () {
          return null
        }
      },
      // 按钮大小
      btnSize: {
        type: String,
        default: function () {
          return 'small'
        }
      },
      btnDisplay: {
        type: Boolean,
        default: function () {
          return true
        }
      },
      // index
      index: {
        type: Number,
        default: function () {
          return null
        }
      },
      // 上传按钮显示内容
      uploadName: {
        type: String,
        default: function () {
          return '上传'
        }
      },
      // 重新上传按钮显示内容
      reUploadName: {
        type: String,
        default: function () {
          return '重新上传'
        }
      },
      // 上传之前方法
      uploadbefore: {
        type: Function,
        default: function () {
          return true
        }
      },
      // 数据回显
      fileLists: {
        type: Array,
        default: function () {
          return []
        }
      },
      // 数据回显类型 text/picture/picture-card
      listType: {
        type: String,
        default: 'text'
      },
      // 限制上传文件个数
      limit: {
        type: Number,
        default: null
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        fullscreenLoading: false,
        newFileName: this.fileName,
        headers: getHeaders(),
        imageUrl: '',
        selected: ''
      }
    },
    computed: {
      sendData: function () {
        return {
          belongCode: this.belongCode,
          belongID: this.belongID
        }
      },
      currentFileId: {
        get: function () {
          return this.fileID
        },
        set: function (val) {
          return this.$emit('update:fileID', val)
        }
      },
      label () {
        // 数据库字段不能为空，默认为零
        return this.UtilJs.isEmpty(this.currentFileId) || this.currentFileId === '0' ? this.uploadName : this.reUploadName
      },
      showFile () {
        return Boolean(this.listType.indexOf('picture-card') > -1)
      }
    },
    created () {
      this.selected = this.value
    },
    watch: {
      'fileID' (val) {
        if (val) {
          this.showImg(val)
        }
      },
      value (val) {
        this.selected = val
      },
      selected (val) {
        if (val === '') {
          this.fileLists = []
        }
        this.$emit('input', val)
      }
    },
    methods: {
      beforeUpload (file) {
        if (!this.uploadbefore(file)) {
          return false
        }
        if (!this.UtilJs.isNull(this.fileSize) && file.size / 1024 > this.fileSize * 1024) {
          this.warning(`已超出上传文件最大限制${this.fileSize}M`)
          return false
        }
        var fileType = '.' + file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
        var banFileTypes = ['.exe', '.bat', '.cmd', '.sh', '.py']
        var banFileTypeFlag = 0
        banFileTypes.forEach(item => {
          if (item === fileType) {
            banFileTypeFlag = 1
          }
        })
        if (banFileTypeFlag === 1) {
          this.warning('不允许上传' + fileType.substring(fileType.lastIndexOf('.') + 1) + '文件')
          return false
        }
        if (!this.UtilJs.isNull(this.fileType)) {
          var fileTypeFlag = 0
          var fileTypeList = this.fileType.toLowerCase().split(',')
          fileTypeList.forEach(it => {
            if (fileType === it) {
              fileTypeFlag = 1
            }
          })
          if (fileTypeFlag === 0) {
            this.warning('只能上传' + this.fileType.toLowerCase().replace(/\./g, '') + '文件')
            return false
          }
        }
        let returnData = {}
        returnData.rowData = this.rowData
        returnData.rowIndex = this.rowIndex
        returnData.index = this.index
        this.$emit('beforeUpload', returnData)
        this.fullscreenLoading = this.$loading({
          lock: true,
          text: '上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return true
      },
      fileRemove (file, fileList) {
        console.log('file', file, fileList)
        console.log('file', file.response.data.fileId, fileList)
        this.$emit('fileRemove', fileList)
      },
      uploadSuccess (response, file, fileList) {
        if (response.code !== 0) {
          this.fullscreenLoading.close()
          this.error(response.message)
          return
        }
        let returnData = {}
        returnData.rowData = this.rowData
        returnData.rowIndex = this.rowIndex
        returnData.index = this.index
        returnData.fileId = response.data.fileId
        this.selected = response.data.fileId
        returnData.fileName = response.data.fileName
        returnData.attachmentId = response.data.fileId
        returnData.nodeName = response.data.fileName
        this.$emit('uploadSuccess', returnData, this.rowIndex, this.rowData, fileList)
        this.fullscreenLoading.close()
        this.showImg(response.data.fileId)
      },
      showImg (val) {
        if (this.listType.indexOf('png') === -1 && this.listType.indexOf('jpg') === -1) return
        let id = ''
        if (val.lastIndexOf(',') === val.length - 1) {
          id = val.substr(0, val.length - 1)
        } else {
          id = val
        }
        this.imageUrl = this.showImageApi + id
        this.$nextTick(() => {
          this.setHeader()
        })
        // this.fileLists.push({})
      },
      // 设置请求头
      setHeader () {
        let img = document.getElementsByClassName('fileImg')[0]
        console.log('img', img)
        let url = this.imageUrl
        let request = new XMLHttpRequest()
        request.responseType = 'blob'
        request.open('get', url, true)
        request.setRequestHeader('Authorization', getToken())
        request.onreadystatechange = e => {
          if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
            img.src = URL.createObjectURL(request.response)
            img.onload = () => {
                URL.revokeObjectURL(img.src)
            }
          }
        }
        request.send(null)
      }
    }
  }
</script>

<style scoped>
  .upload{
    display:inline-block;
    margin: 0 9px 0 1px;
  }
  .btnUpload {
    display: inline-block;
  }
  .btnUpload .fileImg {
    width: 50px;
    height: auto;
    vertical-align: top;
    display: inline-block;
  }
</style>
